#!/usr/bin/env python

import optparse
import os
import sys

import tables

import batchcat
import charmicat


def main():
    '''
    bcat_indices.py [opts] input_files.txt | file.h5 [file.h5 [...]]

    Create indices for the files listed in `input_files.txt' or listed on the command line.
    Indices are generated for columns involved in the default cutset for the analysis
    module specified in the file.
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    
    op.add_option("-c", "--cutset", dest="cutsets", action='append', default=[],
                  help="Apply cutset NAME (can be used more than once)")
    op.add_option("-m", "--module", dest='module_name', default=None, 
                  help="Use module MODULE instead of inferring from input", metavar='MODULE')
    op.add_option("-r", "--replace", action="append", dest="replace", default=[], nargs=2,
                  help="Replace in cutset cut named CUT1 with cut named CUT2")
    op.add_option("-s", dest="list", action='append', default=[],
                  help="Apply the cut NAME (can be used more than once)")
    op.add_option("-x", dest='exclude', action='append', default=[],
                  help="Exclude cut NAME (can be repeated)", metavar='NAME')
    op.add_option("-z", dest='complevel', type='int', default=1,
                  help="Set output compression level 0-9", metavar='0-9')
    op.add_option("--start-on", dest="start_on", default=None,
                  help="Apply only cuts downstream (inclusive) of NAME", metavar='NAME')

    batchcat.add_options(op, omit='outdir')

    opts, args = op.parse_args()
    
    if len(args) == 0:
        msg = "Please supply at least one input file."
        raise charmicat.BadCommandLineError(msg, -1)

    if len(args) == 1:
        if tables.isPyTablesFile(args[0]):
            h5files = [args[0]]
        else:
            with open(args[0]) as fp:
                h5files = [line.strip() for line in fp]
    else:
        h5files = args

    if not opts.module_name:
        opts.module_name = charmicat.module_name_from_paths(h5files)
    
    try:
        module = __import__(opts.module_name)           
    except ImportError:
        msg = "Error importing module `{0}'".format(opts.module_name)
        raise charmicat.BadCommandLineError(msg, -2)

    cut_list = charmicat.build_cut_list(module, opts)

    columns = set()
    with tables.openFile(h5files[0]) as fp:
        for cut in cut_list:
            for c in fp.root.nt._requiredExprVars(cut.pos_str, None, depth=2).keys():
                columns.add(c)
      
    for path in h5files:    
        command = 'python -m batchcat.run.indices {0} {1}'.format(path, ' '.join(columns))

        batchcat.resource_managers['default'].add_job(os.path.basename(path), command, opts)
        

    if opts.bcat_write is None:
        batchcat.resource_managers['default'].submit()
    else:
        batchcat.resource_managers['default'].write(path=opts.bcat_write)

    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except charmicat.BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
